package controller

import (
	"mygo/app/models"
	"mygo/app/services"
	"mygo/app/tools"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type mituoCtl struct {
	db *gorm.DB
}

var Mituo = new(mituoCtl)

var YcMap = map[string]string{
	"沙外渔场":  "YC-01",
	"长江口渔场": "YC-02",
	"舟山渔场":  "YC-03",
	"温台渔场":  "YC-04",
	"闽中渔场":  "YC-05",
	"江外渔场":  "YC-06",
}

var SeaAreaMap = map[string]string{
	"瓯江口海域":  "HY-01",
	"洞头东部海域": "HY-02",
	"南麂列岛海域": "HY-03",
	"乐清湾海域":  "HY-04",
}

var RouteMap = map[string]string{
	"瑞安-北麂航线": "HX-02",
	"鳌江-南麂航线": "HX-03",
}

// GetFisheryData 获取渔业信息getFisheryData
func (ctl *mituoCtl) GetFisheryData(c *gin.Context) {
	ctl.db = models.Db
	foreList := services.GetForeListByCode("yy", ctl.db)
	var foreDetail models.ForeDetailJson
	//获取根据time排序的最新的一条数据
	if ctl.db.Where("foreListId = ? AND state = ?", foreList.Id, "2").Order("time desc").First(&foreDetail).RowsAffected == 0 {
		c.JSON(200, gin.H{
			"code":    0,
			"message": "Fail",
			"data":    nil,
		})
		return
	}
	var forecast models.Forecast
	//将json转换为struct
	services.JsonToStruct(foreDetail.Data, &forecast)
	var fisheryList []models.Fishery
	for i, report := range forecast.Reports {
		if i == 0 {
			for j := 0; j < 6; j++ {
				xs := []string{"24", "48"}
				for hIdx, h := range xs {
					var fishery models.Fishery
					fishery.FisheryID = YcMap[report.Data[2*j+1+hIdx][0].Value]
					fishery.FisheryName = report.Data[2*j+1+hIdx][0].Value
					fishery.PublishTime = foreDetail.Time + " " + "09:00:00"
					fishery.Fh = h
					fishery.WaveHeight = report.Data[2*j+1+hIdx][2].Value
					fishery.WaveLevel = report.Data[2*j+1+hIdx][3].Value

					fisheryList = append(fisheryList, fishery)
				}
			}
		}
	}
	c.JSON(200, gin.H{
		"code":    0,
		"message": "Ok",
		"data":    fisheryList,
	})
}

// getSeaAreaFcst
func (ctl *mituoCtl) GetSeaAreaFcst(c *gin.Context) {
	//	SeaArea
	ctl.db = models.Db
	foreList := services.GetForeListByCode("wzhy", ctl.db)
	var foreDetail models.ForeDetailJson
	//获取根据time排序的最新的一条数据
	if ctl.db.Where("foreListId = ? AND state = ?", foreList.Id, "2").Order("time desc").First(&foreDetail).RowsAffected == 0 {
		c.JSON(200, gin.H{
			"code":    0,
			"message": "Fail",
			"data":    nil,
		})
		return
	}
	var forecast models.Forecast
	//将json转换为struct
	services.JsonToStruct(foreDetail.Data, &forecast)
	var seaAreaList []models.SeaArea
	for i, report := range forecast.Reports {
		if i == 1 {
			for j := 0; j < 4; j++ {
				var seaArea models.SeaArea
				seaArea.Stid = SeaAreaMap[report.Data[j+1][0].Value]
				seaArea.StdName = report.Data[j+1][0].Value
				seaArea.Ptime = foreDetail.Time + " " + "09:00:00"
				seaArea.Fh = "24"
				seaArea.WaveHeight = report.Data[j+1][1].Value
				seaArea.WaveLevel = report.Data[j+1][2].Value
				seaArea.Temp = report.Data[j+1][3].Value
				seaArea.Lon, seaArea.Lat = services.GetLonLatByName(seaArea.StdName)

				seaAreaList = append(seaAreaList, seaArea)
			}
		}
	}
	c.JSON(200, gin.H{
		"code":    0,
		"message": "Ok",
		"data":    seaAreaList,
	})
}

// getRouteFcstData
func (ctl *mituoCtl) GetRouteFcstData(c *gin.Context) {
	ctl.db = models.Db
	foreList := services.GetForeListByCode("rahx", ctl.db)
	var foreDetail models.ForeDetailJson
	//获取根据time排序的最新的一条数据
	if ctl.db.Where("foreListId = ? AND state = ?", foreList.Id, "2").Order("time desc").First(&foreDetail).RowsAffected == 0 {
		c.JSON(200, gin.H{
			"code":    0,
			"message": "Fail",
			"data":    nil,
		})
		return
	}
	var forecast models.Forecast
	//将json转换为struct
	services.JsonToStruct(foreDetail.Data, &forecast)
	var routeList []models.Route
	for i, report := range forecast.Reports {
		if i == 0 {
			for j := 0; j < 2; j++ {
				var route models.Route
				route.RouteID = RouteMap[report.Data[3*j+1][0].Value]
				route.RouteName = report.Data[3*j+1][0].Value
				route.PublishTime = foreDetail.Time + " " + "09:00:00"
				route.Fh = "24"
				route.WaveHeight = report.Data[3*j+1][4].Value
				route.WaveLevel = report.Data[3*j+1][5].Value

				routeList = append(routeList, route)
			}
		}
	}
	c.JSON(200, gin.H{
		"code":    0,
		"message": "Ok",
		"data":    routeList,
	})
}

// getTouismFcstData
func (ctl *mituoCtl) GetTouismFcstData(c *gin.Context) {
	ctl.db = models.Db
	foreList := services.GetForeListByCode("hsyc", ctl.db)
	var foreDetail models.ForeDetailJson
	//获取根据time排序的最新的一条数据
	if ctl.db.Where("foreListId = ? AND state = ?", foreList.Id, "2").Order("time desc").First(&foreDetail).RowsAffected == 0 {
		c.JSON(200, gin.H{
			"code":    0,
			"message": "Fail",
			"data":    nil,
		})
		return
	}
	var forecast models.Forecast
	//将json转换为struct
	services.JsonToStruct(foreDetail.Data, &forecast)
	var beachList []models.Beach
	for i, report := range forecast.Reports {
		if i == 0 {
			for j := 0; j < 1; j++ {
				var beach models.Beach
				beach.Stid = "YC-01"
				beach.StdName = report.Data[j+1][0].Value
				beach.Lon, beach.Lat = "121.064", "27.4602"
				beach.PublishTime = foreDetail.Time + " " + "09:00:00"
				beach.Fh = "24"
				beach.WaveHeight = report.Data[j+1][1].Value
				beach.WaveLevel = report.Data[j+1][2].Value
				beach.Temp = report.Data[j+1][3].Value
				beach.Health = report.Data[j+1][5].Value
				beach.WaterQuality = report.Data[j+1][4].Value
				beach.Swimfitness = report.Data[j+1][6].Value
				beach.SwimSuitableTime = report.Data[j+1][7].Value
				beach.Tip = report.Data[j+1][8].Value

				beachList = append(beachList, beach)
			}
		}
	}
	c.JSON(200, gin.H{
		"code":    0,
		"message": "Ok",
		"data":    beachList,
	})
}

type TideRegionReq struct {
	Stid  string `json:"stid"`
	Start string `json:"start"`
	End   string `json:"end"`
}

// GetTideDataByRegion getTideDataByRegion
var regionTideMap = map[string]string{
	"68": "温州",
	"60": "南麂",
	"59": "北麂",
	"58": "洞头",
	"47": "瑞安",
	"43": "鳌江",
}

func (ctl *mituoCtl) GetTideDataByRegion(c *gin.Context) {
	ctl.db = models.Db
	var tideRegionReq TideRegionReq
	//_ = c.ShouldBindJSON(&tideRegionReq)
	tideRegionReq.Stid = c.Request.FormValue("stid")
	tideRegionReq.Start = c.Request.FormValue("start")
	tideRegionReq.End = c.Request.FormValue("end")
	if tideRegionReq.Start == "" || tideRegionReq.End == "" {
		timeNow := time.Now()
		tideRegionReq.Start = timeNow.Format("2006-01-02")
		tideRegionReq.End = timeNow.AddDate(0, 0, 2).Format("2006-01-02")
	}
	var tideData models.TideData
	tideData.TideID = tideRegionReq.Stid
	//获取逐个小时的潮位
	var offset float64
	if tideRegionReq.Stid == "68" {
		offset = -180
	} else if tideRegionReq.Stid == "60" {
		offset = 0
	} else if tideRegionReq.Stid == "59" {
		offset = 0
	} else if tideRegionReq.Stid == "58" {
		offset = -333
	} else if tideRegionReq.Stid == "47" {
		offset = -186
	} else if tideRegionReq.Stid == "43" {
		offset = -186
	}
	var tideHourList []models.TideHour
	ctl.db.Where("station = ? AND date >= ? AND date <= ?", regionTideMap[tideRegionReq.Stid], tideRegionReq.Start, tideRegionReq.End).Find(&tideHourList)
	for _, v := range tideHourList {
		var tideHour models.TideHourData
		tideHour.DTime = v.Date + " " + v.Time + ":00"
		tideHour.Tide = tools.Float64ToFixedStrZ(tools.StrToFloat64(v.Tide)*100+164+offset, 0, "0")
		tideData.TideHourData = append(tideData.TideHourData, tideHour)
	}

	//获取高低潮
	var twcTideList []models.TwcTide
	ctl.db.Where("station = ? AND date >= ? AND date <= ?", regionTideMap[tideRegionReq.Stid], tideRegionReq.Start, tideRegionReq.End).Find(&twcTideList)
	for _, v := range twcTideList {
		var tideDaily models.TideDailyData
		tideDaily.TideID = tideRegionReq.Stid
		tideDaily.TideDate = v.Date + " 00:00:00"
		tideDaily.FirstHighTide = tools.Float64ToFixedStrZ(tools.StrToFloat64(v.TideHigh1)+offset+164, 0, "0")
		tideDaily.FirstHighTideTime = strings.ReplaceAll(v.TimeHigh1, ":", "") + " "
		tideDaily.FirstLowTide = tools.Float64ToFixedStrZ(tools.StrToFloat64(v.TideLow1)+offset+164, 0, "0")
		tideDaily.FirstLowTideTime = strings.ReplaceAll(v.TimeLow1, ":", "") + " "
		tideDaily.SecondHighTide = tools.Float64ToFixedStrZ(tools.StrToFloat64(v.TideHigh2)+offset+164, 0, "0")
		tideDaily.SecondHighTideTime = strings.ReplaceAll(v.TimeHigh2, ":", "") + " "
		tideDaily.SecondLowTide = tools.Float64ToFixedStrZ(tools.StrToFloat64(v.TideLow2)+offset+164, 0, "0")
		tideDaily.SecondLowTideTime = strings.ReplaceAll(v.TimeLow2, ":", "") + " "
		tideData.TideDailyData = append(tideData.TideDailyData, tideDaily)
	}
	c.JSON(200, gin.H{
		"code":    0,
		"message": "Ok",
		"data":    tideData,
	})
}

func (ctl *mituoCtl) GetTideDataByStation(c *gin.Context) {
	ctl.db = models.Db
	var tideData models.TideData
	name := c.Request.FormValue("name")
	var offset float64
	if name == "瑞安港" {
		name = "瑞安"
		offset = -186
		tideData.TideID = "47"
		tideData.Introduce = "瑞安港作为温州第二大港，拥有经营性码头27座，最大通航船舶为5000吨。可乘潮通航1000吨级货轮，年吞吐量200万吨。\n目前，瑞安港已成为浙南闽北地区重要的商贸集散中心，在瑞安市经济和社会发展中发挥着重要作用。"
	} else if name == "鳌江港" {
		name = "鳌江"
		offset = -186
		tideData.TideID = "43"
		tideData.Introduce = "鳌江港建成于1923年，港口开辟了至湛江、汕头、上海、基隆、大连等全国主要沿海城市航线，成为鳌江流域对外开放的窗口。\n1994年经省政府批准鳌江港为国家二类口岸，并设立了海关、商检、口岸、边防、海事等涉外机构，承担着温州市飞云江以南四个县的全部涉外业务。"
	} else if name == "南麂港" {
		name = "南麂"
		offset = 0
		tideData.TideID = "60"
		tideData.Introduce = "南麂岛位于浙江省平阳县鳌江口外30海里的东海海面上，距市区50海里。是一座旅游岛屿 ，南麂岛是南麂列岛52个岛屿中最大的岛屿。\n南麂岛是一座旅游岛屿 ，是南麂列岛52个岛屿中最大的岛屿。"
	} else if name == "北麂港" {
		name = "北麂"
		offset = 0
		tideData.TideID = "59"
		tideData.Introduce = "北麂港位于北麂岛。西距瑞安港38海里、上海港309海里，南距台湾省基隆港128海里。岸线长275米，水域面积25万平方米，陆域面积4万平方米。\n北麂有5个岙口，建有混凝土结构码头7座，其中大岙、南岙码头在高潮时可停靠50吨位的船只，码道可供小型车辆通行。"
	}

	var tideHourList []models.TideHour
	ctl.db.Where("station = ? AND date = ?", name, time.Now().Format("2006-01-02")).Find(&tideHourList)
	for _, v := range tideHourList {
		var tideHour models.TideHourData
		tideHour.DTime = v.Date + " " + v.Time + ":00"
		tideHour.Tide = tools.Float64ToFixedStrZ(tools.StrToFloat64(v.Tide)*100+164+offset, 0, "0")
		tideData.TideHourData = append(tideData.TideHourData, tideHour)
	}
	//获取高低潮
	var twcTideList []models.TwcTide
	ctl.db.Where("station = ? AND date = ?", name, time.Now().Format("2006-01-02")).Find(&twcTideList)
	for _, v := range twcTideList {
		var tideDaily models.TideDailyData
		tideDaily.TideID = tideData.TideID
		tideDaily.TideDate = v.Date + " 00:00:00"
		tideDaily.FirstHighTide = tools.Float64ToFixedStrZ(tools.StrToFloat64(v.TideHigh1)+offset, 0, "0")
		tideDaily.FirstHighTideTime = strings.ReplaceAll(v.TimeHigh1, ":", "") + " "
		tideDaily.FirstLowTide = tools.Float64ToFixedStrZ(tools.StrToFloat64(v.TideLow1)+offset, 0, "0")
		tideDaily.FirstLowTideTime = strings.ReplaceAll(v.TimeLow1, ":", "") + " "
		tideDaily.SecondHighTide = tools.Float64ToFixedStrZ(tools.StrToFloat64(v.TideHigh2)+offset, 0, "0")
		tideDaily.SecondHighTideTime = strings.ReplaceAll(v.TimeHigh2, ":", "") + " "
		tideDaily.SecondLowTide = tools.Float64ToFixedStrZ(tools.StrToFloat64(v.TideLow2)+offset, 0, "0")
		tideDaily.SecondLowTideTime = strings.ReplaceAll(v.TimeLow2, ":", "") + " "
		tideData.TideDailyData = append(tideData.TideDailyData, tideDaily)
	}
	c.JSON(200, gin.H{
		"code":    0,
		"message": "Ok",
		"data":    tideData,
	})
}

// getWarnList
func (ctl *mituoCtl) GetWarnList(c *gin.Context) {
	ctl.db = models.Db
	warnType := c.Request.FormValue("type")
	finalType := warnType
	if warnType == "天文大潮消息" {
		warnType = "天文潮"
		finalType = "天文大潮"
	}
	page := c.Request.FormValue("page")
	size := c.Request.FormValue("size")
	var warnList models.WarnList
	var AlarmDetailList []models.AlarmDetail
	//	获取type=warnType,page=page,size=size的数据
	ctl.db.Where("type = ? AND state = ? AND region = ?", warnType, "1", "wz").Offset((tools.StrToInt(page) - 1) * tools.StrToInt(size)).Limit(tools.StrToInt(size)).Find(&AlarmDetailList)
	for _, v := range AlarmDetailList {
		var warn models.WarnDetail
		warn.IssueNo = v.Bh
		warn.TypeStr = "发布"
		warn.Wlevel = services.GetWlevel(v.PubType, v.Level)
		warn.IsEnable = "1"
		warn.ValidTime = "24"
		warn.PublishTime = v.Time + ":00"
		warn.Content = v.Data + "\n" + v.Data1
		warn.Name = finalType + v.PubType
		warn.ContentTail = ""
		warn.FileName = v.FileName
		warn.WarnProID = strconv.Itoa(int(v.Id))
		warn.Num = "1"
		warnList.Data = append(warnList.Data, warn)
	}
	//获取type=warnType的数量
	var total int64
	ctl.db.Model(&models.AlarmDetail{}).Where("type = ? AND state = ? AND region = ?", warnType, "1", "wz").Count(&total)
	warnList.Total = strconv.FormatInt(total, 10)

	c.JSON(200, gin.H{
		"code":    0,
		"message": "Ok",
		"data":    warnList,
	})
}

// getWarnDetailed
func (ctl *mituoCtl) GetWarnDetailed(c *gin.Context) {
	ctl.db = models.Db
	id := c.Request.FormValue("id")
	var warnDetail models.WarnDetail2
	var alarmDetail models.AlarmDetail
	ctl.db.Where("bh = ? AND region = ?", id, "wz").First(&alarmDetail)
	warnDetail.ID = alarmDetail.Bh
	warnDetail.WarnType = alarmDetail.Type
	warnDetail.WarnLevel = services.GetWlevel(alarmDetail.PubType, alarmDetail.Level)
	warnDetail.Ptime = alarmDetail.Time + ":00"
	warnDetail.Title = alarmDetail.Type + alarmDetail.PubType
	warnDetail.Content = alarmDetail.Data + "\n" + alarmDetail.Data1
	warnDetail.ContentImg = ""
	warnDetail.ContentTail = ""
	warnDetail.FileName = alarmDetail.FileName
	warnDetail.WarnProID = strconv.Itoa(int(alarmDetail.Id))
	c.JSON(200, gin.H{
		"code":    0,
		"message": "Ok",
		"data":    warnDetail,
	})
}

// getLastWarn
func (ctl *mituoCtl) GetLastWarn(c *gin.Context) {
	ctl.db = models.Db
	warnType := c.Request.FormValue("type")
	finalType := warnType
	if warnType == "天文大潮消息" {
		warnType = "天文潮"
		finalType = "天文大潮"
	}
	var alarmDetail models.AlarmDetail
	if ctl.db.Where("type = ? AND state = ? AND region = ?", warnType, "1", "wz").Order("time desc").First(&alarmDetail).RowsAffected == 0 {
		c.JSON(200, gin.H{
			"code":    0,
			"message": "Fail",
			"data":    []models.WarnDetailLast{},
		})
		return
	}
	var warnDetail models.WarnDetailLast
	warnDetail.IssueNo = alarmDetail.Bh
	warnDetail.Name = finalType + alarmDetail.PubType
	warnDetail.PublishTime = alarmDetail.Time + ":00"
	warnDetail.WarnLevel = services.GetWlevel(alarmDetail.PubType, alarmDetail.Level)
	warnDetail.WarnType = finalType
	warnDetail.Content = alarmDetail.Data + "\n" + alarmDetail.Data1
	warnDetail.ContentTail = ""

	if finalType == "天文大潮" || alarmDetail.PubType == "警报解除通报" {
		//获取当前时间
		timeNow := time.Now()
		timeNowStr := timeNow.Format("2006-01-02 15:04")
		hourGaps := tools.GetHourGap(alarmDetail.Time, timeNowStr)
		if hourGaps > 24 {
			c.JSON(200, gin.H{
				"code":    0,
				"message": "Ok",
				"data":    []models.WarnDetailLast{},
			})
			return
		}
	}

	c.JSON(200, gin.H{
		"code":    0,
		"message": "Ok",
		"data":    warnDetail,
	})
}

// getIndexLastWarn
func (ctl *mituoCtl) GetIndexLastWarn(c *gin.Context) {
	ctl.db = models.Db
	typeArr := []string{"海浪", "风暴潮"}
	var warnDetailList []models.WarnDetailIndexLast
	for _, warnType := range typeArr {
		var alarmDetail models.AlarmDetail
		if ctl.db.Where("type = ? AND state = ? AND region = ?", warnType, "1", "wz").Order("time desc").First(&alarmDetail).RowsAffected == 0 {
			continue
		}
		//判断PublishTime距离当前时间是否超过24小时
		timeNow := time.Now()
		timeNowStr := timeNow.Format("2006-01-02 15:04")
		hourGaps := tools.GetHourGap(alarmDetail.Time, timeNowStr)
		if hourGaps > 24 {
			continue
		}
		var warnDetail models.WarnDetailIndexLast
		warnDetail.IssueNo = alarmDetail.Bh
		warnDetail.Name = alarmDetail.Type + alarmDetail.PubType
		warnDetail.PublishTime = alarmDetail.Time + ":00"
		warnDetail.WarnLevel = services.GetWlevel(alarmDetail.PubType, alarmDetail.Level)
		warnDetail.WarnType = alarmDetail.Type
		warnDetail.Num = "1"
		warnDetailList = append(warnDetailList, warnDetail)
	}
	c.JSON(200, gin.H{
		"code":    0,
		"message": "Ok",
		"data":    warnDetailList,
	})

	//var warnDetail models.WarnDetailIndexLast
	//var alarmDetail models.AlarmDetail
	//ctl.db.Where("state = ? AND region = ?", "1", "wz").Order("time desc").First(&alarmDetail)
	//warnDetail.IssueNo = alarmDetail.Bh
	//if alarmDetail.Type == "天文潮" {
	//	alarmDetail.Type = "天文大潮"
	//}
	//warnDetail.Name = alarmDetail.Type + alarmDetail.PubType
	//warnDetail.PublishTime = alarmDetail.Time + ":00"
	//warnDetail.WarnLevel = services.GetWlevel(alarmDetail.PubType, alarmDetail.Level)
	//warnDetail.WarnType = alarmDetail.Type
	//warnDetail.Num = "1"
	//
	//if alarmDetail.Type == "天文大潮" || alarmDetail.PubType == "警报解除通报" {
	//	//获取当前时间
	//	timeNow := time.Now()
	//	timeNowStr := timeNow.Format("2006-01-02 15:04")
	//	hourGaps := tools.GetHourGap(alarmDetail.Time, timeNowStr)
	//	if hourGaps > 24 {
	//		c.JSON(200, gin.H{
	//			"code":    0,
	//			"message": "Ok",
	//			"data":    []models.WarnDetailIndexLast{},
	//		})
	//		return
	//	}
	//}
	//c.JSON(200, gin.H{
	//	"code":    0,
	//	"message": "Ok",
	//	"data": []models.WarnDetailIndexLast{warnDetail},
	//})
}

// getTideWarnData
func (ctl *mituoCtl) GetTideWarnData(c *gin.Context) {
	ctl.db = models.Db
	//var tideWarnList []models.TideWarn
	//ctl.db.Where("state = ? AND region = ?", "1", "wz").Order("time desc").Find(&tideWarnList)
	c.JSON(200, gin.H{
		"code":    0,
		"message": "Ok",
		"data":    []int{},
	})
}

// getTideStation
func (ctl *mituoCtl) GetTideStation(c *gin.Context) {

}
